package com.fzshang.shopping.wx.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzshang.shopping.commen.bean.*;
import com.fzshang.shopping.commen.controller.BaseController;
import com.fzshang.shopping.commen.entity.ApiResult;
import com.fzshang.shopping.commen.util.exception.CommonException;
import com.fzshang.shopping.commen.util.sms.Code;
import com.fzshang.shopping.commen.util.sms.EhcacheUtil;
import com.fzshang.shopping.commen.util.sms.SenSms;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 微信信息 前端控制器
 * </p>
 *
 * @author 冯政尚
 * @since 2020-03-03
 */
@Controller
@RequestMapping("wx/user")
public class WXUserController extends BaseController {

    @Value("${weixin.redirectURL}")
    String redirectURL = "";

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ApiOperation(value = "用户登陆")
    public String getUser(@ApiParam(name = "code", value = "微信回调的code", required = true) String code, String state, HttpServletRequest request) throws WxErrorException, WxPayException {

        //token换用户基本信息 如果出现异常 则说明是刷新  重新重定向授权地址
        try {
            //code换token
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = xbxWxService.getWxService().oauth2getAccessToken(code);

            WxMpUser wxMpUser = xbxWxService.getWxService().oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
            User user = userService.login(wxMpUser);
            request.getSession().setAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            //微信授权的地址
            String url = xbxWxService.getWxService().oauth2buildAuthorizationUrl(redirectURL, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
            return "redirect:" + url;
        }
        System.out.println("state:"+state);
        // xbxWxService.mpPayOrder();
        if (state != null && !state.equals("")) {
            return state;
        } else {
            return "redirect:/wx/user/index";
        }
    }

    /**
     * @return 微信首页
     */
    @RequestMapping(value = "index")
    public String index(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        user = userService.getById(user.getId());
        session.setAttribute("user", user);
        System.out.println("user:"+user);
        model.addAttribute("user",user);
        model.addAttribute("wheelPlanting",wheelPlantingService.list());
        //必推好货
        QueryWrapper   queryWrapper = new QueryWrapper();
        queryWrapper.eq("state",1);
        Good good = goodService.getOne(queryWrapper);
        model.addAttribute("quality",good);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("good_id",good.getId());
        List<GoodImage> goodImages = goodImageService.list(queryWrapper1);
        for (int i = 0; i < goodImages.size(); i++) {
            model.addAttribute("image",goodImages.get(0).getUrl());
        }
        //冰点秒杀
        QueryWrapper  queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("state",2);
        Good good1 = goodService.getOne(queryWrapper2);
        model.addAttribute("point",good1);
        QueryWrapper queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq("good_id",good1.getId());
        List<GoodImage> goodImages1 = goodImageService.list(queryWrapper3);
        for (int i = 0; i < goodImages1.size(); i++) {
            model.addAttribute("url",goodImages1.get(0).getUrl());
        }
        //查询首页图标i
        QueryWrapper queryWrapper4 = new QueryWrapper();
        queryWrapper4.eq("state",1);
        List<CommodityClassification> list = commodityClassificationService.list(queryWrapper4);
        model.addAttribute("list",list);
        if(user.getTel()==null){
            model.addAttribute("tel",0);
        }else{
            model.addAttribute("tel",1);
        }
        return "wx/index";
    }
    /**
     * @return 微信首页
     */
    @RequestMapping(value = "a")
    public String a(HttpServletRequest request,Model model){
        model.addAttribute("user",getWxUser(request));
        return "wx/a";
    }

    /**
     * @return 个人中心
     */
    @RequestMapping(value = "personal.html")
    public String personal(HttpServletRequest request,Model model){
        User user = getWxUser(request);
        model.addAttribute("user",user);
        if(user.getTel()==null){
            model.addAttribute("tel",0);
        }else{
            model.addAttribute("tel",1);
        }
        //查询购物袋
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("openid",user.getOpenid());
        model.addAttribute("shoppingCar",shoppingCarService.list(queryWrapper).size());
        return "wx/personal";
    }
    /**
     * @return 绑定后台
     */
    @RequestMapping(value = "binding_background.html")
    public String binding_background(HttpServletRequest request,Model model){
        model.addAttribute("user",getWxUser(request));
        return "wx/personal/binding_background";
    }

    /**
     * @param openId
     * @param userInfoId
     * @return 微信绑定后台
     */
    @RequestMapping(value = "updateByOpenId")
    @ResponseBody
    public ApiResult updateByOpenId(String openId,Long userInfoId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",userInfoId);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if(userInfo!=null){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("openid",openId);
            User user = userService.getOne(queryWrapper1);
            user.setUserInfoId(userInfoId);
            user.setId(user.getId());
            if(userService.updateById(user)){
                return ApiResult.ok();
            }
        }
        return ApiResult.fail("失败!");
    }

    /**
     * @param
     * @return 跳转商品管理
     */
    @RequestMapping(value = "good.html")
    public String good(HttpServletRequest request,Model model){
        User user1 = getWxUser(request);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("openid",user1.getOpenid());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if(userInfo==null){
            return "wx/personal/good/failNull";
        }else{
            if(userInfo.getState()==1){
                return "wx/personal/good/fail";
            }else{
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("user_id",userInfo.getId());
                List<Good> goods = goodService.list(queryWrapper1);
                System.out.println("qweqewqe:"+goods);
                model.addAttribute("good",goods);
                //循环每一个商品查找每一个商品的第一张图片就是主图
                for (int i = 0; i < goods.size(); i++) {
                    QueryWrapper queryWrapper2 = new QueryWrapper();
                    queryWrapper2.eq("good_id",goods.get(i).getId());
                    List<GoodImage> goodImages = goodImageService.list(queryWrapper2);
                    goods.get(i).setGoodUrl(goodImages.get(0).getUrl());
                }
                return "wx/personal/good/good";
            }
        }
    }

    /**
     * @param
     * @return 跳转收益分析
     */
    @RequestMapping(value = "chart.html")
    public String chart(Model model){
        String today= DateUtil.today();
        String str = today.substring(0,4);
        model.addAttribute("time",str);
        return "wx/personal/chart";
    }
    /**
     * @param
     * @return 邀请开店
     */
    @RequestMapping(value = "set_up_shop.html")
    public String set_up_shop(Model model,HttpServletRequest request){
        model.addAttribute("user",getWxUser(request));
        return "wx/personal/set_up_shop";
    }

    /**
     * @param
     * @return 更多分类
     */
    @RequestMapping(value = "more.html")
    public String more(Model model){
        List<CommodityClassification> commodityClassification = commodityClassificationService.list();
        model.addAttribute("commodity",commodityClassification);
        model.addAttribute("one",commodityClassification.get(0).getId());

        return "wx/index/more";
    }

    /**
     * @param
     * @return 跳转地址
     */
    @RequestMapping(value = "address.html")
    public String address(Model model,HttpServletRequest request){
        model.addAttribute("user",getWxUser(request));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",getWxUser(request).getId());
        model.addAttribute("address",addressService.list(queryWrapper));
        return "wx/personal/address/address";
    }

    /**
     * @param
     * @return 商家入驻
     */
    @RequestMapping(value = "business.html")
    public String business(Model model,HttpServletRequest request){
        model.addAttribute("user",getWxUser(request));
        //查询商家入住租费
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state",1);
        Money money = moneyService.getOne(queryWrapper);
        model.addAttribute("money",money.getMoney());
        return "wx/personal/business";
    }

    /**
     * @return 发送验证码
     */
    @RequestMapping(value = "sendSms" ,method = RequestMethod.GET)
    @ResponseBody
    public ApiResult updatePhoneNumber(@RequestParam String phone) {
        CommonResponse response;
        String code= Code.createCodeShu();
        try {
            response =  SenSms.send(phone,code);
        } catch (ClientException e) {
            e.printStackTrace();
            return ApiResult.fail("服务器出错，请稍后再试");
        }
        //验证码获取成功后
        JSONObject jsonObject = JSONUtil.parseObj(response.getData());
        if(jsonObject.get("Message").equals("触发小时级流控Permits:5")){
            return ApiResult.fail("一个小时只能发送5条短信");
        }else if(jsonObject.get("Message").equals("触发分钟级流控Permits:1")){
            return ApiResult.fail("一分钟只能发送一条短信");
        }else if(jsonObject.get("Message").equals("触发天级流控Permits:10")){
            return ApiResult.fail("一天只能发送十条短信");
        } else if(jsonObject.get("Message").equals("OK")){
            //存进cache缓存  180后过期  当访问过一次后 60秒内没有再此访问 同样过期 缓存区的key设置成数字加字符串 否则获取不到
            EhcacheUtil.put("phone",phone,code);
            System.out.println("用户手机号: "+phone);
            System.out.println("验证码: "+code);
            System.err.println("----------------------------------");
            return  ApiResult.ok("获取验证码成功");
        }else{
            return  ApiResult.fail("获取短信验证码失败");
        }
    }

    /**
     * @return 校验验证码
     */
    @RequestMapping(value = "equalsCache", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult equalsCache(@RequestParam String phone,@RequestParam String code) {
        String cachCode = EhcacheUtil.get("phone", phone) + "";
        if (code.equals(cachCode)) {
            return ApiResult.ok();
        } else {
            return ApiResult.fail();
        }
    }



    /**
     * @return 绑定手机号
     */
    @RequestMapping(value = "phone.html")
    public String phone (Model model,HttpServletRequest request){
        model.addAttribute("user",getWxUser(request));
        return "wx/phone";
    }

    /**
     * @param phone
     * @return 绑定手机号
     */
    @RequestMapping(value = "updatePhone")
    @ResponseBody
    public ApiResult updatePhone(String phone,Long userId){
        User user = userService.getById(userId);
        user.setTel(phone);
        if(userService.updateById(user)){
            return ApiResult.ok();
        }
        return ApiResult.fail();
    }

    /**
     * @param model
     * @param request
     * @return 跳购物车
     */
    @RequestMapping(value = "shoppingCar.html")
    public String shoppingCar(Model model,HttpServletRequest request){
        User user = getWxUser(request);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("openid",user.getOpenid());
        List<ShoppingCar> shoppingCars = shoppingCarService.list(queryWrapper);
        List<Good> goods = new ArrayList<>();
        for (int i = 0; i < shoppingCars.size(); i++) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("id",shoppingCars.get(i).getGoodId());
            Good good = goodService.getOne(queryWrapper1);
            good.setShoppingCarId(shoppingCars.get(i).getId());
            goods.add(good);
        }
        System.out.println("购物车:"+goods);
        //查询第一张图片
        for (int i = 0; i < goods.size(); i++) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("good_id",goods.get(i).getId());
            List<GoodImage> goodImages = goodImageService.list(queryWrapper1);
            goods.get(i).setGoodUrl(goodImages.get(0).getUrl());
        }
        if(goods.size()>0){
            model.addAttribute("size",1);
            model.addAttribute("good",goods);
        }else{
            model.addAttribute("size",0);
        }

        return "wx/personal/shoppingCar/shoppingCar";
    }


}
